package com.cst.intercepterdemo.chain;

import com.cst.intercepterdemo.chain.node.IIntercepterChainNode;
import com.cst.intercepterdemo.context.IInterceptContext;
import org.springframework.util.StringUtils;

/**
 * <ul>
 * <li>文件名称 : com.cst.intercepterdemo.chain.IntercepterChain
 * </li>
 * <li>版权所有 : 版权所有(C)2016-2020</li>
 * <li>公 司 : CST</li>
 * <li>创建时间 : 2016/12/2</li>
 * <li>修改记录 : </li>
 * </ul>
 * 类说明：责任链
 *
 * @author Allen
 * @version 1.0
 */
public class IntercepterChain implements IIntercepterChain {

    public IntercepterChain(IIntercepterChainNode firstChainNode, String chainName) {

        if(firstChainNode==null){
            throw new RuntimeException("Chain node is empty");
        }
        if(StringUtils.isEmpty(chainName)){
            throw new RuntimeException("Chain name is empty");
        }

        this.firstChainNode = firstChainNode;
        this.chainName = chainName;

        this.chainLength = countChainNode();
    }

    private IIntercepterChainNode firstChainNode;

    private String chainName;

    private int chainLength;

    @Override
    public boolean intercept(IInterceptContext context) {
        return firstChainNode.dochain(context);
    }

    @Override
    public int chainLength() {
        return chainLength;
    }

    @Override
    public String getChainName() {
        return chainName;
    }

    private int countChainNode(){
        int i = 1;
        IIntercepterChainNode chainNode = this.firstChainNode;
        while(chainNode.hasNext()){
            chainNode = chainNode.next();
        }
        return i;
    }

}
